package ctimer
{
	import flash.events.TimerEvent;
	import flash.utils.Timer;

	public class CTimer
	{
		private var taskList:Array;
		private var timer:flash.utils.Timer;

		public function CTimer(){
			
			taskList = new Array();
			
			timer = new Timer(1000);
		}
		
		public function AddTask(task:Task):void{
		
			if (task != null){
				taskList.push(task);
			}
		}
	
		public function DeleteTask(task:Task):void{
		
			var taskIndex:uint;
			
			taskIndex = taskList.indexOf(task);
			if (taskIndex != -1){
				delete(taskList[taskIndex]);
			}
		}
		
		public function Run():void{
			timer.addEventListener(TimerEvent.TIMER, OnTimer);
			timer.start();
		}
		
		public function Stop():void{
			timer.stop();
		}
		
		public function ClearTaskList():void{

			taskList.splice(0, taskList.length);
		}
		
		private function OnTimer(even:TimerEvent):void{
			
			var task:Task = null;
			var taskIndex:uint;
			for (taskIndex=0; taskIndex<taskList.length; taskIndex++){
				
				task = taskList[taskIndex] as Task;
				if (task != null){
					
					task.LastTime--;
					if (task.LastTime == 0){
						task.TaskFun();
						
						if (task.IsCycle){
							task.LastTime = task.Time;
						} else {
							DeleteTask(task);
						}
					}
				
					task = null;
					
				}//end if (task != null)
				
			}//end for
		}
		
	}
}